package com.yh.interceptor;

import com.yh.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 动态更新用户的登录状态，刷新用户登录信息在缓存中的过期时间
 *
 * @author yuhuan
 * @date 2022/01/13
 */
public class UpdateLoginTimeInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestUri = request.getRequestURI();
        if (requestUri.contains(Constants.CLIENT_PATH)) {
            // 获取用户信息
            String token = request.getHeader("token");
            // 如果用户已经登录，就更新用户的登录时间
            if (!ObjectUtils.isEmpty(token)) {
                String userIdInRedis = Constants.LoginData.LOGIN_DATA_PREFIX_KEY + ":" + token;
                if (redisTemplate.hasKey(userIdInRedis)) {
                    redisTemplate.expire(userIdInRedis, Constants.LoginData.LOGIN_EXPIRE_TIME, TimeUnit.MINUTES);
                }
            }
            return true;
        }
        return true;
    }
}
